<template>
  <el-card shadow="never"
           :loading="loading"
           class="tree-select-card">
    <el-input v-model="filterText"
              prefix-icon="Search"
              :placeholder="placeholder"
              clearable />

    <el-tree ref="treeRef"
             class="mt-2"
             :data="treeData"
             :props="defaultProps"
             :expand-on-click-node="false"
             default-expand-all
             :filter-node-method="handleFilter"
             @node-click="handleNodeClick"
             highlight-current />
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch, watchEffect } from 'vue'
import { ElTree } from 'element-plus'

interface Props {
  data: any[]
  props?: {
    children: string
    label: string
    disabled?: string
  }
  placeholder?: string
}

// 设置属性默认值
const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  props: () => ({
    children: 'children',
    label: 'label',
    disabled: 'false',
  }),
  placeholder: '请输入关键字',
})

// 定义事件
const emit = defineEmits(['node-click'])

// 树形组件引用
const treeRef = ref<InstanceType<typeof ElTree>>()
// 搜索关键字
const filterText = ref('')
// 树形数据
const treeData = ref<any[]>([])
// 配置项
const defaultProps = ref(props.props)
// 添加加载状态
const loading = ref(false)

// 监听搜索框值变化
watchEffect(
  () => {
    if (treeRef.value) {
      treeRef.value.filter(filterText.value)
    }
  },
  { flush: 'post' }
)

// 优化树形数据的监听
watch(
  () => props.data,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      treeData.value = newVal
    }
  },
  { deep: true, immediate: true }
)

// 处理节点点击
const handleNodeClick = (data: any) => {
  emit('node-click', data)
}

// 处理节点过滤
const handleFilter = (value: string, data: any) => {
  if (!value) return true
  return data[props.props.label as string]?.includes(value)
}

// 暴露方法给父组件
defineExpose({
  treeRef,
})
</script>

<style scoped>


/* 树形选择卡片 */
.tree-select-card {
  height: 100%;
}
/* 高亮当前节点 */
:deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content ){
  background-color: #009688;
  color: #fff;
}
/* 滚动条样式 */
.mt-2 {
  flex: 1;
  height: auto;
  overflow-y: hidden; /* 初始隐藏滚动条 */
  margin-top: 10px;
  scrollbar-width: thin;
  scrollbar-color: rgba(144, 147, 153, 0.3) transparent;
}

/*鼠标移入时显示滚动条*/
.tree-select-card:hover .mt-2 {
  overflow-y: auto;
}

/* Webkit（Chrome）浏览器滚动条美化 */
.mt-2::-webkit-scrollbar {
  width: 6px;
}
.mt-2::-webkit-scrollbar-thumb {
  background-color: rgba(144, 147, 153, 0.3);
  border-radius: 3px;
}
.mt-2::-webkit-scrollbar-track {
  background-color: transparent;
}
</style>
